package org.yczbj.ycvideoplayer.slice.music;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbPalette;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Slider;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSubscriber;
import ohos.event.commonevent.MatchingSkills;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.audio.AudioManager;
import ohos.media.audio.AudioRemoteException;
import ohos.rpc.RemoteException;

import com.yc.music.config.MusicConstant;
import com.yc.music.config.PlayModeEnum;
import com.yc.music.inter.OnPlayerEventListener;
import com.yc.music.model.AudioBean;
import com.yc.music.tool.BaseAppHelper;
import com.yc.music.utils.MusicLogUtils;
import com.yc.music.utils.MusicSpUtils;

import org.yczbj.ycvideoplayer.ResourceTable;

/**
 * PlayMusicFragment
 *
 * @since 2021-05-10
 */
public class PlayMusicFragment extends Fraction implements Component.ClickedListener, OnPlayerEventListener {
    private static final long SECOND_IN_MILLIS = 1000L;
    private static final String TAG = "DetailAudioFragment";
    private static final int DELAY_TIME = 300;
    private Image ivBack;
    private Text tvTitle;
    private Text tvArtist;
    private Slider sbVolume;
    private Text tvCurrentTime;
    private Slider sbProgress;
    private Image ivMode;
    private Image ivPrev;
    private Image ivPlay;
    private Image ivNext;
    private Image ivOther;
    private int mLastProgress;
    /**
     * 是否拖进度，默认是false
     */
    private boolean isDraggingProgress;
    private AudioManager mAudioManager;
    private AbilitySlice mSlice;
    private int mPlayMode = 1;
    /**
     * 发送广播接收者
     */
    private CommonEventSubscriber mVolumeReceiver = new CommonEventSubscriber(
        new CommonEventSubscribeInfo(new MatchingSkills())) {
        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
            try {
                sbVolume.setProgressValue(mAudioManager.getVolume(AudioManager.AudioVolumeType.STREAM_MUSIC));
            } catch (AudioRemoteException e) {
                MusicLogUtils.e(e.getMessage());
            }
        }
    };

    @Override
    protected void onComponentDetach() {
        super.onComponentDetach();
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        Component component = scatter.parse(getContentView(), container, false);
        initView(component);
        initListener();
        initData();
        return component;
    }

    /**
     * 对Fragment传递数据，建议使用setArguments(Bundle args)，而后在onCreate中使用getArguments()取出，
     * 在 “内存重启”前，系统会帮你保存数据，不会造成数据的丢失。和Activity的Intent恢复机制类似。
     *
     * @param type type
     * @return PlayMusicFragment实例对象
     */
    public static PlayMusicFragment newInstance(String type) {
        Intent intent = new Intent();
        intent.setParam(TAG, type);
        PlayMusicFragment fragment = new PlayMusicFragment();
        return fragment;
    }

    /**
     * 返回监听
     */
    public void onBackPressed() {
        ((MusicPlayerSlice) mSlice).onBackPressed();
        ivBack.setEnabled(false);
        runMainThread(new Runnable() {
            @Override
            public void run() {
                ivBack.setEnabled(true);
            }
        });
    }

    /**
     * 切换任务到主线程执行
     *
     * @param runnable 执行的runnable
     */
    public void runMainThread(Runnable runnable) {
        EventRunner eventRunner = EventRunner.getMainEventRunner();
        EventHandler eventHandler = new EventHandler(eventRunner);
        eventHandler.postTask(runnable, DELAY_TIME);
    }

    @Override
    public void onStop() {
        super.onStop();
        try {
            CommonEventManager.unsubscribeCommonEvent(mVolumeReceiver);
        } catch (RemoteException e) {
            MusicLogUtils.e(e.getMessage());
        }
    }

    @Override
    public void onActive() {
        super.onActive();
        try {
            CommonEventManager.subscribeCommonEvent(mVolumeReceiver);
        } catch (RemoteException e) {
            MusicLogUtils.e(e.getMessage());
        }
    }

    public int getContentView() {
        return ResourceTable.Layout_fragment_play_music;
    }

    /**
     * 初始化界面
     *
     * @param component 容器
     */
    public void initView(Component component) {
        initFindById(component);
        initSliderStyle(sbVolume);
        initSliderStyle(sbProgress);
        initPlayMode();
        initVolume();
    }

    private void initFindById(Component component) {
        ivBack = (Image) component.findComponentById(ResourceTable.Id_iv_back);
        tvTitle = (Text) component.findComponentById(ResourceTable.Id_tv_title);
        tvArtist = (Text) component.findComponentById(ResourceTable.Id_tv_artist);
        sbVolume = (Slider) component.findComponentById(ResourceTable.Id_sb_volume);
        tvCurrentTime = (Text) component.findComponentById(ResourceTable.Id_tv_current_time);
        sbProgress = (Slider) component.findComponentById(ResourceTable.Id_sb_progress);
        ivMode = (Image) component.findComponentById(ResourceTable.Id_iv_mode);
        ivPrev = (Image) component.findComponentById(ResourceTable.Id_iv_prev);
        ivPlay = (Image) component.findComponentById(ResourceTable.Id_iv_play);
        ivNext = (Image) component.findComponentById(ResourceTable.Id_iv_next);
        ivOther = (Image) component.findComponentById(ResourceTable.Id_iv_other);
    }

    /**
     * 设置slider样式
     *
     * @param slider 进度条
     */
    private void initSliderStyle(Slider slider) {
        ShapeElement progressElement = new ShapeElement();
        progressElement.setRgbColor(RgbPalette.WHITE);
        slider.setProgressElement(progressElement);
    }

    /**
     * 初始化控件监听
     */
    public void initListener() {
        ivBack.setClickedListener(this);
        ivMode.setClickedListener(this);
        ivPlay.setClickedListener(this);
        ivPrev.setClickedListener(this);
        ivNext.setClickedListener(this);
        ivOther.setClickedListener(this);
        initSeekBarListener();
    }

    private void initSeekBarListener() {
        Slider.ValueChangedListener onSeekBarChangeListener = new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int progress, boolean isB) {
                if (slider == sbProgress) {
                    if (Math.abs(progress - mLastProgress) >= SECOND_IN_MILLIS) {
                        mLastProgress = progress;
                    }
                }
            }

            /**
             * 通知用户已启动触摸手势,开始触摸时调用
             *
             * @param slider slider
             */
            @Override
            public void onTouchStart(Slider slider) {
                if (slider == sbProgress) {
                    isDraggingProgress = true;
                }
            }

            /**
             * 通知用户已结束触摸手势,触摸结束时调用
             *
             * @param slider slider
             */
            @Override
            public void onTouchEnd(Slider slider) {
                if (slider == sbProgress) {
                    isDraggingProgress = false;

                    // 如果是正在播放，或者暂停，那么直接拖动进度
                    if (BaseAppHelper.get().getMusicService().isPlaying()
                        || BaseAppHelper.get().getMusicService().isPausing()) {
                        // 获取进度
                        int progress = slider.getProgress();

                        // 直接移动进度
                        BaseAppHelper.get().getMusicService().seekTo(progress);
                    } else {
                        // 其他情况，直接设置进度为0
                        slider.setProgressValue(0);
                    }
                } else if (slider == sbVolume) {
                    mAudioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, slider.getProgress());
                }
            }
        };
        sbProgress.setValueChangedListener(onSeekBarChangeListener);
        sbVolume.setValueChangedListener(onSeekBarChangeListener);
    }

    /**
     * 初始化数据
     */
    public void initData() {
        setViewData(BaseAppHelper.get().getMusicService().getPlayingMusic());
    }

    @Override
    public void onClick(Component component) {
        int id = component.getId();
        if (id == ResourceTable.Id_iv_back) {
            onBackPressed();
        } else if (id == ResourceTable.Id_iv_mode) {
            setImage(++mPlayMode);
            switchPlayMode();
        } else if (id == ResourceTable.Id_iv_play) {
            play();
        } else if (id == ResourceTable.Id_iv_next) {
            next();
        } else if (id == ResourceTable.Id_iv_prev) {
            prev();
        }
    }

    /**
     * 设置播放模式图片
     *
     * @param playMode 播放模式索引
     */
    private void setImage(int playMode) {
        if (mPlayMode == 1) {
            ivMode.setPixelMap(ResourceTable.Media_ic_play_btn_loop_pressed);
        } else if (mPlayMode == 2) {
            ivMode.setPixelMap(ResourceTable.Media_ic_play_btn_shuffle);
        } else {
            ivMode.setPixelMap(ResourceTable.Media_ic_play_btn_one);
        }
        if (playMode == 3) {
            mPlayMode = 0;
        }
    }

    private void prev() {
        if (BaseAppHelper.get().getMusicService() != null) {
            BaseAppHelper.get().getMusicService().prev();
        }
    }

    private void next() {
        if (BaseAppHelper.get().getMusicService() != null) {
            BaseAppHelper.get().getMusicService().next();
        }
    }

    private void play() {
        if (BaseAppHelper.get().getMusicService() != null) {
            BaseAppHelper.get().getMusicService().playPause();
        }
    }

    private void switchPlayMode() {
        int playMode = MusicSpUtils.getInstance(MusicConstant.SP_NAME).getInt(MusicConstant.PLAY_MODE, 0);
        PlayModeEnum mode = PlayModeEnum.valueOf(playMode);
        switch (mode) {
            case LOOP:
                mode = PlayModeEnum.SHUFFLE;
                break;
            case SHUFFLE:
                mode = PlayModeEnum.SINGLE;
                break;
            case SINGLE:
                mode = PlayModeEnum.LOOP;
                break;
            default:
                break;
        }
        MusicSpUtils.getInstance(MusicConstant.SP_NAME).put(MusicConstant.PLAY_MODE, mode.value());
        initPlayMode();
    }

    private void initPlayMode() {
        MusicSpUtils.getInstance(MusicConstant.SP_NAME).getInt(MusicConstant.PLAY_MODE, 0);
    }

    /**
     * 初始化音量
     */
    private void initVolume() {
        mAudioManager = new AudioManager(getContext());
        if (mAudioManager != null) {
            try {
                sbVolume.setMaxValue(mAudioManager.getMaxVolume(AudioManager.AudioVolumeType.STREAM_MUSIC));
                sbVolume.setProgressValue(mAudioManager.getVolume(AudioManager.AudioVolumeType.STREAM_MUSIC));
            } catch (AudioRemoteException e) {
                MusicLogUtils.e(e.getMessage());
            }
        }
    }

    /**
     * 填充页面数据
     *
     * @param playingMusic 正在播放的音乐
     */
    private void setViewData(AudioBean playingMusic) {
        if (playingMusic == null) {
            return;
        }
        tvTitle.setText(playingMusic.getTitle());
        tvArtist.setText(playingMusic.getArtist());
        sbProgress.setProgressValue((int) BaseAppHelper.get().getMusicService().getCurrentPosition());
        sbProgress.setViceProgress(0);
        sbProgress.setMaxValue((int) playingMusic.getDuration());
        mLastProgress = 0;
        tvCurrentTime.setText("00:00");
        if (BaseAppHelper.get().getMusicService().isPlaying() || BaseAppHelper.get().getMusicService().isPreparing()) {
            ivPlay.setSelected(true);
        } else {
            ivPlay.setSelected(false);
        }
    }

    /**
     * onChange
     *
     * @param music music
     */
    @Override
    public void onChange(AudioBean music) {
        setViewData(music);
    }

    @Override
    public void onPlayerStart() {
        ivPlay.setSelected(true);
    }

    @Override
    public void onPlayerPause() {
        ivPlay.setSelected(false);
    }

    @Override
    public void onUpdateProgress(long progress) {
        if (progress > 0) {
            // 如果没有拖动进度，则开始更新进度条进度
            if (!isDraggingProgress) {
                sbProgress.setProgressValue((int) progress);
            }
        }
    }

    @Override
    public void onBufferingUpdate(int percent) {
        if (sbProgress.getMax() > 0 && percent > 0) {
            MusicLogUtils.e("setOnPlayEventListener---percent---" + sbProgress.getMax() + "-----" + percent);
            sbProgress.setViceProgress(sbProgress.getMax() * 100 / percent);
        }
    }

    @Override
    public void onTimer(long remain) {
    }

    /**
     * 获取slice
     *
     * @param slice slice实例
     */
    public void setSlice(AbilitySlice slice) {
        mSlice = slice;
    }
}
